package com.tqz.zookeeper.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * {@link ZooKeeper} 连接工具类.
 *
 * @author <a href="https://github.com/tian-qingzhao">tianqingzhao</a>
 * @since 2025/9/4 16:41
 */
@Slf4j
public class ZookeeperUtil {

    public static final String ZK_URL = "127.0.0.1:2181";

    public static ZooKeeper create() {
        try {
            // 使用门栓保证主线程获取zk对象的时候连接建立成功
            final CountDownLatch connectionLatch = new CountDownLatch(1);

            ZooKeeper zooKeeper = new ZooKeeper(ZK_URL, 60000, event -> {
                // EventType有以下几种类型
                // None: 连接建立事件
                // NodeCreated： 节点创建
                // NodeDeleted： 节点删除
                // NodeDataChanged：节点数据变化
                // NodeChildrenChanged：子节点列表变化
                // DataWatchRemoved：节点监听被移除
                // ChildWatchRemoved：子节点监听被移除

                if (event.getType() == Watcher.Event.EventType.None
                        && event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    connectionLatch.countDown();
                    log.info("节点：{} 连接建立成功", event.getPath());
                }
            });

            connectionLatch.await();

            return zooKeeper;
        } catch (Exception e) {
            throw new RuntimeException("连接异常：" + e);
        }
    }

    public static String formatStat(Stat stat) {
        return "czxid:" + stat.getCzxid() + ", mzxid:" + stat.getMzxid() + ", ctime:" + stat.getCtime() +
                ", mtime:" + stat.getMtime() + ", version:" + stat.getVersion() +
                ", aversion:" + stat.getAversion() + ", ephemeralOwner:" +
                stat.getEphemeralOwner() + ", dataLength:" + stat.getDataLength() +
                ", numChildren:" + stat.getNumChildren() + ", pzxid:" + stat.getPzxid();
    }
}
